package com.esiran.payadmin.util;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public final class ImageIOUtilEx {
    /**
     * 覆盖模板图片
     * @param tmplImage 模板图片
     * @param targetImage 覆盖图片
     * @param targetXy 目标位置
     */
    public static BufferedImage coverImageTmpl(
            BufferedImage tmplImage,
            BufferedImage targetImage,
            int[] targetXy){
        if (targetXy.length < 2){
            return null;
        }
        // 获取模板图片的宽高值
        int tmplWidth = tmplImage.getWidth();
        int tmplHeight = tmplImage.getHeight();
        // 新建一个图片缓存对象
        BufferedImage newBi = new BufferedImage(tmplWidth,tmplHeight,BufferedImage.TYPE_INT_RGB);
        // 创建绘制对象
        Graphics2D g = newBi.createGraphics();
        // 绘制源模板图片
        g.drawImage(tmplImage, 0, 0, tmplWidth, tmplHeight, null);
        // 获取模板图片的宽高值
        int targetWidth = targetImage.getWidth();
        int targetHeight =targetImage.getHeight();
        // 设置混合模式
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 1.0f));
        int widthDiff = tmplWidth - targetWidth;
        int heightDiff = tmplHeight - targetHeight;
        if (targetXy[0] < 0){
            targetXy[0] = widthDiff/2;
        }else if (targetXy[0] > widthDiff){
            targetXy[0] = widthDiff;
        }
        if (targetXy[1] < 0){
            targetXy[1] = heightDiff/2;
        }else if (targetXy[0] > widthDiff){
            targetXy[1] = heightDiff;
        }
        g.drawImage(targetImage,targetXy[0],targetXy[1],targetWidth,targetHeight,null);
        g.dispose();
        return newBi;
    }
    public static BufferedImage coverImageTmpl4text(
            BufferedImage tmplImage,
            String targetText,
            int fontSize,
            Color fontColor,
            int[] targetXy){
        return coverImageTmpl4text(tmplImage,targetText,fontSize,fontColor,targetXy,false);
    }
    public static BufferedImage coverImageTmpl4text(
            BufferedImage tmplImage,
            String targetText,
            int fontSize,
            Color fontColor,
            int[] targetXy,
            boolean multipleLine){
        if (targetXy.length < 2){
            return null;
        }
        // 获取模板图片的宽高值
        int tmplWidth = tmplImage.getWidth();
        int tmplHeight = tmplImage.getHeight();
        // 新建一个图片缓存对象
        BufferedImage newBi = new BufferedImage(tmplWidth,tmplHeight,BufferedImage.TYPE_INT_RGB);
        // 创建绘制对象
        Graphics2D g = newBi.createGraphics();
        // 绘制源模板图片
        g.drawImage(tmplImage, 0, 0, tmplWidth, tmplHeight, null);
        Font font = new Font("ShanghaiFace-QingxiaGB", Font.PLAIN, fontSize);
        //获取文字所占的像素
        FontRenderContext context = g.getFontRenderContext();
        Rectangle2D stringBounds = font.getStringBounds(targetText,context);
        int targetWidth = (int) stringBounds.getWidth();
        int targetHeight = (int) stringBounds.getHeight();
        if (!multipleLine){
            int widthDiff = tmplWidth - targetWidth;
            int heightDiff = tmplHeight - targetHeight;
            if (targetXy[0] < 0){
                targetXy[0] = widthDiff/2;
            }else if (targetXy[0] > widthDiff){
                targetXy[0] = widthDiff;
            }
            if (targetXy[1] < 0){
                targetXy[1] = heightDiff/2;
            }else if (targetXy[0] > widthDiff){
                targetXy[1] = heightDiff;
            }
        }
        // 设置混合模式
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 1.0f));
        g.setFont(font);
        g.setColor(fontColor);
        // 设置抗锯齿效果
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
        if (multipleLine){
            drawMultipleLineText(g,targetText,targetXy[0],targetXy[1]);
        }else{
            g.drawString(targetText,targetXy[0],targetXy[1]);
        }
        g.dispose();
        return newBi;
    }
    private static void drawMultipleLineText(Graphics2D g,String text,int x,int y){
        for (String line : text.split("\n"))
            g.drawString(line, x, y += g.getFontMetrics().getHeight());
    }
    public static String image2base64(BufferedImage bi,String formatName){
        ByteArrayOutputStream outputStream = null;
        try {
            outputStream = new ByteArrayOutputStream();
            ImageIO.write(bi,formatName,outputStream);
        } catch (IOException e) {
            return null;
        }
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(outputStream.toByteArray());
    }
    public static BufferedImage image4url(String url){
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            ResponseBody body = response.body();
            if (body == null) {
                return null;
            }
            return ImageIO.read(body.byteStream());
        }catch (IOException e){
            return null;
        }
    }
}
